import time
import network
import camera
import socket
from machine import Pin

# 配置区
WIFI_SSID = "LAPTOP-D3RPTUAA 6358"
WIFI_PWD = "19234949992.ch"
S3_IP = "192.168.137.100"  # ESP32-S3的IP
S3_PORT = 80               # S3的TCP接收端口
CAMERA_RESOLUTION = 2      # 320x240，减轻传输压力

# 硬件初始化
led = Pin(4, Pin.OUT)
led.value(0)

def init_camera():
    try:
        camera.init()
        camera.framesize(CAMERA_RESOLUTION)
        camera.quality(20)
        print("摄像头初始化成功")
        return True
    except Exception as e:
        print(f"摄像头错误: {e}")
        return False

def init_wifi():
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    wlan.connect(WIFI_SSID, WIFI_PWD)
    
    # 等待连接
    for _ in range(20):
        if wlan.isconnected():
            ip = wlan.ifconfig()[0]
            print(f"WiFi已连接，IP: {ip}")
            led.value(1)
            return ip
        time.sleep(0.5)
    print("WiFi连接失败")
    return None

def send_to_s3():
    """持续捕获图像并发送到S3"""
    while True:
        try:
            # 创建TCP连接
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.connect((S3_IP, S3_PORT))
            print(f"已连接到S3: {S3_IP}:{S3_PORT}")
            
            while True:
                # 捕获图像
                frame = camera.capture()
                if not frame:
                    time.sleep(0.1)
                    continue
                
                # 发送格式：4字节长度 + 图像数据（便于S3解析）
                s.send(len(frame).to_bytes(4, "big"))  # 先发送长度
                s.send(frame)                          # 再发送图像
                led.value(1)
                time.sleep(0.1)  # 控制帧率
                led.value(0)
                
        except Exception as e:
            print(f"传输错误: {e}")
            s.close()
            time.sleep(2)  # 重连间隔

def main():
    if not init_camera():
        return
    ip = init_wifi()
    if ip:
        send_to_s3()
    camera.deinit()
    led.value(0)

if __name__ == "__main__":
    main()
